package com.demo2do.fms.admin.web.controller.supplier.appraisal;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.fms.admin.entity.search.supplier.SupplierSearch;
import com.demo2do.fms.admin.entity.security.Login;
import com.demo2do.fms.admin.service.supplier.AppraisalResultService;
import com.demo2do.fms.admin.service.supplier.SupplierService;
import com.demo2do.fms.admin.web.resolver.Secure;
import com.demo2do.fms.entity.appraisal.AppraisalResult;
import com.demo2do.fms.entity.appraisal.AppraisalResultItem;
import com.demo2do.fms.entity.appraisal.AppraisalType;
import com.demo2do.fms.entity.supplier.common.Supplier;

/**
 * 分属供方绩效结果查询（不包含一般供方）
 * 
 *  一级供方可以看到他的二级供方的绩效结果
 *  总部，分区看全部供方
 * 
 * @author Wy
 * @author Ark
 *
 */
@Controller
@RequestMapping("/supplier-appraisal-results")
@MenuSetting("menu-supplier")
public class SupplierAppraisalResultController {
    
    @Autowired
    private SupplierService supplierService;
    
    @Autowired
    private AppraisalResultService appraisalResultSerive;
    
    /**
     * list
     * 
     * @param login
     * @param page
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-performance-supplier-appraisal-result-search")
    public ModelAndView list(@Secure Login login) {

        ModelAndView modelAndView = new ModelAndView("supplier/appraisal/supplier-appraisal-result/supplier-appraisal-result-list");
        
        List<Supplier> subSuppliers = supplierService.listSubSupplier(login);
        List<String> subSupplierIds = CollectionUtils.extractPropertyList(subSuppliers, "idString");
        
        int totals = appraisalResultSerive.countByTarget(subSupplierIds);
        if(totals > 0) {
            
            List<AppraisalResult> appraisalResults = appraisalResultSerive.listByTarget(subSupplierIds);
            List<String> targets = CollectionUtils.extractPropertyList(appraisalResults, "target");
            
            List<Long> supplierIds = new ArrayList<Long>();
            for(String target : targets) {
                supplierIds.add(Long.parseLong(target));
            }
            
            List<Supplier> suppliers = supplierService.list(supplierIds);
            modelAndView.addObject("suppliers", suppliers);
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * search panel
     * 
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public ModelAndView search() {
        ModelAndView modelAndView = new ModelAndView("supplier/appraisal/supplier-appraisal-result/supplier-appraisal-result-search");
        return modelAndView;
    }
    
    /**
     * search
     * 
     * @param login
     * @param search
     * @param page
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-performance-supplier-appraisal-result-search")
    public ModelAndView onSearch(@Secure Login login, SupplierSearch search, Page page) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/appraisal/supplier-appraisal-result/supplier-appraisal-result-list");
        
        List<Long> loginSupplierIds = supplierService.listSubSupplierId(login);
        search.addSupplierIds(loginSupplierIds);
        
        List<Supplier> subSuppliers = supplierService.listSupplier(search);
        List<String> subSupplierIds = CollectionUtils.extractPropertyList(subSuppliers, "idString");
        
        int totals = appraisalResultSerive.countByTarget(subSupplierIds);
        if(totals > 0) {
            
            List<AppraisalResult> appraisalResults = appraisalResultSerive.listByTarget(subSupplierIds);
            List<String> targets = CollectionUtils.extractPropertyList(appraisalResults, "target");
            
            List<Long> supplierIds = new ArrayList<Long>();
            for(String target : targets) {
                supplierIds.add(Long.parseLong(target));
            }
            
            List<Supplier> suppliers = supplierService.list(supplierIds);
            modelAndView.addObject("suppliers", suppliers);
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * view
     * 
     * @param supplierId
     * @param page
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/{supplierId}", method = RequestMethod.GET)
    @MenuSetting("submenu-performance-supplier-appraisal-result-search")
    public ModelAndView view(@PathVariable("supplierId") String supplierId, @Secure Login login) {

        ModelAndView modelAndView = new ModelAndView("supplier/appraisal/supplier-appraisal-result/supplier-appraisal-result-view");
        
        int totals = appraisalResultSerive.countByTarget(supplierId, login);
        if (totals > 0) {
            
            // 1. list result
            List<AppraisalResult> appraisalResults = appraisalResultSerive.listByTarget(supplierId, login);
            modelAndView.addObject("appraisalResults", appraisalResults);
            
            // 2. construct Map<resultId, List<AppraisalResultItem>>
            List<Long> resultIds = CollectionUtils.extractPropertyList(appraisalResults, "id");
            List<AppraisalResultItem> appraisalResultItems = appraisalResultSerive.listByResult(resultIds);
            Map<String, List<AppraisalResultItem>> appraisalResultItemMaps = CollectionUtils.constructMapValues(appraisalResultItems, "result.id");
            modelAndView.addObject("appraisalResultItemMaps", appraisalResultItemMaps);
            
            // 3. list scores/appraisal.name
            if (login.isAdminUser() || login.isSuper()) {
                Date timeAgo = DateUtils.addMonths(new Date(), -18);
                List<AppraisalResult> timeAgoResults = appraisalResultSerive.listByTarget(supplierId, timeAgo, AppraisalType.ADMIN);
                
                List<BigDecimal> scoreTotals = CollectionUtils.extractPropertyList(timeAgoResults, "scoreTotal");
                List<String> appraisalNames = CollectionUtils.extractPropertyList(timeAgoResults, "appraisal.name");
                modelAndView.addObject("scoreTotals", StringUtils.join(scoreTotals, ","));
                modelAndView.addObject("appraisalNames", StringUtils.join(appraisalNames, ","));
            }
            
        }
        
        modelAndView.addObject("login", login);

        return modelAndView;
        
    }
    
}
